import os
from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT

def merge_txt_files_to_word(directory, output_filename):
    # 创建一个新的 Word 文档
    doc = Document()

    # 遍历指定目录中的所有文件
    for filename in os.listdir(directory):
        if filename.endswith('.txt'):
            file_path = os.path.join(directory, filename)
            with open(file_path, 'r', encoding='utf-8') as file:
                content = file.read()

            # 添加标题
            title = doc.add_heading(filename, level=1)
            title.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER

            # 添加内容
            doc.add_paragraph(content)

            # 添加一个空行
            doc.add_paragraph('')

    # 保存 Word 文档
    output_path = os.path.join(directory, output_filename)
    doc.save(output_path)
    print(f"文件已保存到 {output_path}")

def main():
    # 获取用户输入的目录
    directory = input("请输入包含 .txt 文件的目录路径: ")
    if not os.path.isdir(directory):
        print("指定的路径不是一个有效的目录。")
        return

    # 获取用户输入的输出文件名
    output_filename = input("请输入输出 Word 文档的文件名（不包括扩展名）: ")
    output_filename += ".docx"

    # 合并 .txt 文件到 Word 文档
    merge_txt_files_to_word(directory, output_filename)

if __name__ == "__main__":
    main()